package cn.lyvust.shili04;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
 * Description:
 * date: 2021-5-25 20:19
 *
 * @author Guo_guo
 * @since JDK 1.8
 */
public class TestDB {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/student?user=root&password=123456";
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url);
        // 必须在connection上设置事务是否自动提交，默认是true，现修改为false
        conn.setAutoCommit(false);
        String sql1 = "UPDATE account SET balance = balance - ? WHERE name= ? ;";
        String sql2 = "UPDATE account SET balance = balance + ? where name= ? ;";
        BigDecimal bd = new BigDecimal(1000);
        PreparedStatement ps = conn.prepareStatement(sql1);
        ps.setBigDecimal(1, bd);
        ps.setString(2, "张三");
        ps.executeUpdate(); // 提交sql1的语句
        if (bd.equals(new BigDecimal(1000))) {
//            conn.rollback();
//            throw new RuntimeException("故意抛出运行时异常");
        }
        ps = conn.prepareStatement(sql2);
        ps.setBigDecimal(1, bd);
        ps.setString(2, "李四");
        ps.executeUpdate();
        // 事务的提交
        conn.commit();
        conn.close();
    }
}
